package com.glsc.ngateway.common.base.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author: qiyr
 * @date: 2022/4/25 13:57
 * @description: 表格number型数据读取自定转换器
 */
public class ExcelDoubleConverter implements Converter<Double> {

    private static final Logger logger = LoggerFactory.getLogger(ExcelDoubleConverter.class);
    private static final String ERR_MESSAGE_FORMAT = "列：[{0}] 的数据转换为数字类型失败，已设置为空";
    private static final List<String> FILTER_CHARACTER = Arrays.asList("/", "-");

    @Override
    public Class supportJavaTypeKey() {
        return Number.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (cellData == null) {
            return null;
        }
        String value = cellData.toString();
        if (!StringUtils.hasText(value) || FILTER_CHARACTER.contains(value)) {
            logger.warn(MessageFormat.format(ERR_MESSAGE_FORMAT, contentProperty.getHead().getHeadNameList().get(0)));
            return null;
        }
        return Double.parseDouble(cellData.toString());
    }

    @Override
    public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData<>(value);
    }

    public static Double cellToDouble(Map<Integer, Cell> dataMap, Integer column) {
        CellData data = (CellData) dataMap.get(column);
        if (data == null || !StringUtils.hasText(data.toString())) {
            logger.warn(MessageFormat.format(ERR_MESSAGE_FORMAT, column));
            return null;
        }
        try {
            return Double.parseDouble(data.toString());
        } catch (Exception e) {
            return null;
        }
    }

    public static Double cellToDoubleNotNull(Map<Integer, Cell> dataMap, Integer column) {
        CellData data = (CellData) dataMap.get(column);
        if (data == null || !StringUtils.hasText(data.toString())) {
            throw new NullPointerException("数值转换异常，单元格数据为空");
        }
        return Double.parseDouble(data.toString());
    }
}
